<?php

namespace Application\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
use Application\Model\Role as Role;

class SejourFicheTable
{
    protected $table ='Sejour_fiche';
    protected $tableName ='Sejour_fiche';
    
    protected $tableGateway;
    protected $authService;

    public function __construct(TableGateway $tableGateway)
    {
    	$this->tableGateway = $tableGateway;
    }
    
    public function fetchAll($id)
    {
        $resultSet = $this->tableGateway->select(function(Select $select) use($id) {
            $select->where->equalTo('sejourId', $id);
        	$select->order('idFiche ASC');
        });
        
        return $resultSet;
    }
    
    public function fetchAllArray($id)
    {
    	$resultSet = $this->fetchAll($id);
    
    	$entities = array();
    
    	foreach ($resultSet as $row) {
    		$sejour = new SejourFiche();
    		$sejour->exchangeArray( (array) $row);
    		$entities[] = $sejour;
    	}
    
    	return $entities;
    }

    public function getSejourFiche($id)
    {
        $id = (int) $id;

        $rowset = $this->tableGateway->select(array('idFiche' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }
    
    public function saveFicheEntry(SejourFiche $sejourDatas)
    {
        $data = (array) $sejourDatas;
        
        $id = (int)$sejourDatas->idFiche;
        
        if ($id == 0) {
            $this->tableGateway->insert($data);
            
            $id = $this->tableGateway->lastInsertValue;
            
        } else {
            if ($this->getSejourFiche($id)) {
                $this->tableGateway->update($data, array('idFiche' => $id));
            } else {
                throw new \Exception('Form id does not exist');
            }
        }
        
        return $id;
    }
    
    public function deleteFicheEntry($id)
    {
        $this->tableGateway->delete(array('idFiche' => $id));
    }

    public function deleteFicheEntries($id)
    {
        $this->tableGateway->delete(array('sejourId' => $id));
    }
}